package com.jasiri.project.ui.process.page

import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Typeface
import android.provider.ContactsContract
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jasiri.project.R
import com.jasiri.project.adapter.ProcessContactInfoAdapter
import com.jasiri.project.databinding.PageProcessCommonBinding
import com.jasiri.project.pro.ProFragment
import com.jasiri.project.ui.process.activity.ProcessActivity
import com.jasiri.project.utils.DensityUtils
import com.jasiri.project.utils.LanguageUtils
import com.jasiri.project.utils.StringDeepCopy
import com.jasiri.project.utils.event.EventType
import com.jasiri.project.utils.event.track.TrackEventManager
import com.jasiri.project.utils.helper.ActivityStackHelper
import com.jasiri.project.utils.http.AppUrls.addCommonParams
import com.jasiri.project.utils.log.HHLog
import com.jasiri.project.utils.rv.LinearDecoration
import com.jasiri.lib.baseadapter.JasiriBaseAdapterUtil.getColor
import com.jasiri.project.app.App
import com.jasiri.project.lib.dev.JasiriSysDataHelper
import org.json.JSONArray
import org.json.JSONObject
import java.util.regex.Pattern

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/4/18 11:29
 * @Annotation：流程 - 联系人信息
 */
class ContactPage(): ProFragment() {
    private var _binding: PageProcessCommonBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    private var stepAct: ProcessActivity? = null
    private var stepItem: JSONObject? = null
    //内容列表
    private var mContactAdapter: ProcessContactInfoAdapter? = null
    private var cacheContactItem = ""

    constructor(act: ProcessActivity,data: JSONObject): this(){
        this.stepAct = act
        this.stepItem = data
    }
    override fun getRootView(inflater: LayoutInflater): View {
        _binding = PageProcessCommonBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        rootViewBinding.containerLayout.setBackgroundColor(ContextCompat.getColor(requireContext(),R.color.transparent))
        initRvList()
    }

    override fun initListener() {
        //添加
        _binding?.contactAddOne?.setOnClickListener {
            if (cacheContactItem.isNotEmpty()){
                mContactAdapter?.addLastItem(JSONObject(cacheContactItem))
                mContactAdapter?.notifyDataSetChangedWrapper()
            }

            mContactAdapter?.let {
                //最多添加50个联系人
                _binding?.contactAddOne?.isEnabled = it.itemCount < 50
            }
        }

        //下一步
        _binding?.btnNext?.setOnClickListener {
            _binding?.root?.clearFocus()
            if (!isAllowSubmit()){
                showToast(getString(R.string.tips_submit_error))
                return@setOnClickListener
            }
            stepItem?.let { stepData ->
                val params = JSONObject().addCommonParams().apply {
                    put("path",stepData.optString("apiUrl").replace("/",""))
                }
                //拼接上传数据格式
                val paramArray = JSONArray()
                mContactAdapter?.let { adapter ->
                    for (i in 0..< adapter.itemCount){
                        val obj = JSONObject()
                        val dataArray = adapter.getItem(i).optJSONArray("dataList")
                        dataArray?.let {
                            for (j in 0..< it.length()){
                                val item = it.optJSONObject(j)
                                val paramName = item.optString("paramName")
                                val selectItem = item.optJSONObject("selectItem")
                                var paramValue = selectItem?.optString("value")
                                if (paramName == "relation" && paramValue == item.optString("relationOtherKey")){
                                    paramValue = selectItem?.optString("otherValue")
                                    //如果关系为“Other”，输入的内容为纯数字，则直接传“Other”
                                    if (isSikadwaAllNumber(paramValue)){
                                        paramValue = item.optString("relationOtherKey")
                                    }
                                }
                                obj.put(paramName,paramValue)
                            }
                        }
                        paramArray.put(obj)
                    }
                }
                params.put(stepData.optString("contactParamName"),paramArray)

                //立即上报
                TrackEventManager.trackEventNow(String.format(EventType.CLICK.CLICK_STEP_XX_NEXT,stepData.optString("stepTitle")),"")
                //上报位置和陀螺仪数据
                JasiriSysDataHelper.onCheckSubmitDataByTypes(App.instance(), arrayListOf("T11","T12"),stepData.optString("stepTitle"))

                val act = context as ProcessActivity
                act.submitAction(params)
            }
        }
    }

    override fun initData() {
        if (stepItem == null){
            ActivityStackHelper.finishActivity(ProcessActivity::class.java)
            return
        }

        _binding?.stepTipsLayout?.visibility = View.GONE
        _binding?.contactAddOne?.visibility = View.GONE
        _binding?.approvedTipsLayout?.visibility = View.GONE
        _binding?.amountPlusLayout?.visibility = View.GONE
        stepItem?.let {
            _binding?.contactAddOne?.visibility = View.VISIBLE
            _binding?.textStepTips?.setTextColor(getColor(R.color.FF74A967))
            val showRepayTime = getString(R.string.process_contact_info_tips_repay_time)
            val showNot = getString(R.string.process_contact_info_tips_not)
            val showText = String.format(getString(R.string.process_contact_info_tips),showRepayTime,showNot)
            val startRepayTimIndex = showText.indexOf(showRepayTime)
            val startNotIndex = showText.indexOf(showNot)
            val dataSecuritySpannable = SpannableString(showText)
            dataSecuritySpannable.setSpan(ForegroundColorSpan(getColor(R.color.FF55721C)), startRepayTimIndex, startRepayTimIndex + showRepayTime.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            dataSecuritySpannable.setSpan(StyleSpan(Typeface.BOLD), startRepayTimIndex, startRepayTimIndex + showRepayTime.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            dataSecuritySpannable.setSpan(ForegroundColorSpan(getColor(R.color.FF55721C)), startNotIndex, startNotIndex + showNot.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            dataSecuritySpannable.setSpan(StyleSpan(Typeface.BOLD), startNotIndex, startNotIndex + showNot.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            _binding?.textStepTips?.text = dataSecuritySpannable
            _binding?.stepTipsIcon?.setImageResource(R.mipmap.img_process_contact_info_tips_icon)
            _binding?.stepTipsLayout?.setBackgroundResource(R.drawable.process_contact_info_tips_bg)
            _binding?.stepTipsLayout?.visibility = View.VISIBLE

            val showApprovedKey1 = getString(R.string.process_face_submit_approved_tips_over)
            val showApprovedKey2 = getString(R.string.process_face_submit_approved_tips_days)
            val showApprovedText = String.format(getString(R.string.process_face_submit_approved_tips),showApprovedKey1,showApprovedKey2)
            val startApprovedIndex1 = showApprovedText.indexOf(showApprovedKey1)
            val startApprovedIndex2 = showApprovedText.indexOf(showApprovedKey2)
            val approvedTipsSpannable = SpannableString(showApprovedText)
            approvedTipsSpannable.setSpan(ForegroundColorSpan(getColor(R.color.FF00CB48)), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            approvedTipsSpannable.setSpan(ForegroundColorSpan(getColor(R.color.FF00CB48)), startApprovedIndex2, startApprovedIndex2 + showApprovedKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            //加粗
            approvedTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            approvedTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startApprovedIndex2, startApprovedIndex2 + showApprovedKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            _binding?.textApprovedTips?.text = approvedTipsSpannable
            _binding?.approvedTipsLayout?.visibility = View.VISIBLE

            _binding?.textAmountPlus?.text = String.format(getString(R.string.process_loan_amount_plus),it.optString("limitAmount"))
            _binding?.amountPlusLayout?.visibility = View.VISIBLE
        }

        //联系人关系关键字
        val contactRelationOther = getString(R.string.process_contact_info_relation_other)
        val contactRelationOtherHint = getString(R.string.process_contact_info_relation_other_hint)
        //是否支持通讯录选择联系人
        val isContactPick = isSikadwaContactPick()
        stepItem?.let { itemData ->
            // TODO: 这里dataList需要深拷贝，否则列表会共用一个数据源
            val stringCopy = StringDeepCopy(itemData.optString("dataList"))
            val dataList = arrayListOf<JSONObject>()
            for (i in 0..< itemData.optInt("itemCount")){
                val obj = JSONObject()
                val dataArray = JSONArray(stringCopy.content)
                for (j in 0..<dataArray.length()){
                    val dataObj = dataArray.optJSONObject(j)
                    dataObj.put("isContactPick",isContactPick)
                    dataObj.put("title",dataObj.optString("title"))
                    when(dataObj.optString("action")){
                        "CONTACT_GROUP_RELATION",
                        "SELECT" -> {
                            dataObj.put("action","CONTACT_GROUP_RELATION")
                            var relationShips = itemData.optJSONArray("relationShips")
                            if (LanguageUtils.isSwahili()){
                                relationShips = itemData.optJSONArray("relationShips_sw")
                            }
                            val valueArray = relationShips?.optJSONArray(i)
                            valueArray?.let {
                                //手动添加一条Other
                                it.put(contactRelationOther)
                                val values = JSONArray()
                                for (n in 0..< it.length()){
                                    val value = JSONObject()
                                    value.put("title",it.optString(n))
                                    if (LanguageUtils.isSwahili()){
                                        value.put("title_sw", it.optString(n))
                                    }
                                    value.put("value",it.optString(n))
                                    values.put(value)
                                }
                                dataObj.put("values",values)
                            }
                            dataObj.put("relationOtherKey",contactRelationOther)
                            dataObj.put("relationOtherHint",contactRelationOtherHint)
                        }
                        "CONTACT_GROUP_PHONE" -> {//联系电话
                            dataObj.put("action","CONTACT_GROUP_PHONE")
                        }
                        "CONTACT_GROUP_NAME" -> {//联系人姓名
                            dataObj.put("action","CONTACT_GROUP_PHONE")
                        }
                        else -> {
                            dataObj.put("action","CONTACT_GROUP_PHONE")
                        }
                    }
                }
                obj.put("stepTitle",stepItem?.optString("stepTitle"))
                obj.put("dataList",dataArray)
                dataList.add(obj)
            }
            mContactAdapter?.data = dataList
        }
        //缓存最后一个联系人item数据，用户新增item
        cacheContactItem = StringDeepCopy(mContactAdapter?.lastItem.toString()).content

        addEvent(EventType.PAGE.PAGE_STEP_CONTACT_START,"")
    }

    /**
     * 初始化页面内容列表
     */
    private fun initRvList() {
//        _binding?.rvCommon?.setHasFixedSize(true)
        _binding?.rvCommon?.isNestedScrollingEnabled = false
        _binding?.rvCommon?.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        _binding?.rvCommon?.layoutManager = layoutManager
        val topDecoration = DensityUtils.dp2px(14f)
        _binding?.rvCommon?.addItemDecoration(LinearDecoration(0, 0, 0, topDecoration))
        mContactAdapter = ProcessContactInfoAdapter(binding.root,_binding?.rvCommon)
        _binding?.rvCommon?.adapter = mContactAdapter
        _binding?.rvCommon?.itemAnimator = DefaultItemAnimator()
        mContactAdapter?.setOnChildItemSelectMobileListener(object : ProcessContactInfoAdapter.IChildItemSelectMobileListener {
            override fun onChildSelectMobileClick(parentPosition: Int, childModel: JSONObject) {
                stepAct?.let {
                    val startTime = System.currentTimeMillis()
                    it.pickContact?.startPickCnt { contactName, contactMobile ->
                        HHLog.e(">>>>>>>>>>>>>>>>>>>>>$contactName>>>>>>>$contactMobile")
                        val subTimestamp = System.currentTimeMillis() - startTime
                        val parentItem = mContactAdapter?.getItem(parentPosition)
                        //设置联系人名称
                        val dataArray = parentItem?.optJSONArray("dataList")
                        if (dataArray != null) {
                            for (i in 0..<dataArray.length()) {
                                val itemObj = dataArray.optJSONObject(i)
                                if (itemObj.optString("paramName") == "fullName"){
                                    val obj = JSONObject()
                                    obj.put("title",contactName)
                                    obj.put("value",contactName)
                                    itemObj.put("selectItem",obj)
                                    val subRemark = "${contactName}$$${subTimestamp}"
                                    addEvent(String.format(EventType.CLICK.CLICK_STEP_XX_SELECT, "${parentItem.optString("stepTitle")}_${itemObj.optString("paramName")}_${parentPosition+1}"), subRemark)
                                    continue
                                }
                                if (itemObj.optString("paramName") == "mobile"){
                                    val obj = JSONObject()
                                    obj.put("title",contactMobile)
                                    obj.put("value",contactMobile)
                                    itemObj.put("selectItem",obj)
                                    val subRemark = "${contactMobile}$$${subTimestamp}"
                                    addEvent(String.format(EventType.CLICK.CLICK_STEP_XX_SELECT, "${parentItem.optString("stepTitle")}_${itemObj.optString("paramName")}_${parentPosition+1}"), subRemark)
                                    continue
                                }
                            }
                        }
                        mContactAdapter?.notifyItemChanged(parentPosition)

//                    val obj = JSONObject()
//                    obj.put("title",contactMobile)
//                    obj.put("value",contactMobile)
//                    childModel.put("selectItem", obj)
//                    mContactAdapter?.notifyItemChanged(parentPosition)
//
//                    addEvent(String.format(EventType.CLICK.CLICK_STEP_XX_SELECT, childModel.optString("paramName")), "$contactName:$contactMobile")
                    }
                }
            }
        })
    }

    /**
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isAllowSubmit(): Boolean{
        val dataList = arrayListOf<JSONObject>()
        mContactAdapter?.let { adapter ->
            for (i in 0..< adapter.itemCount){
                val dataArray = adapter.getItem(i).optJSONArray("dataList")
                dataArray?.let {
                    for (j in 0..< it.length()){
                        val item = it.optJSONObject(j)
                        dataList.add(item)
                    }
                }
            }
        }
        //是否允许提交
        var isAllow = true
        for (i in 0..<dataList.size){
            val item = dataList[i]
            //存在 isMust && isMust == ”NO“  非必填
            if (item.has("isMust") && item.optString("isMust") == "NO"){
                continue
            }
            //必填 && 没有内容 || 内容为空
            if (!item.has("selectItem")){
                isAllow = false
                break
            }
            val selectItem = item.optJSONObject("selectItem")
            if (selectItem == null){
                isAllow = false
                break
            }
            val paramName = item.optString("paramName")
            val paramValue = selectItem.optString("value")
            if (paramValue.isEmpty()){
                isAllow = false
                break
            }
            if (paramName == "relation" && paramValue == item.optString("relationOtherKey") && selectItem.optString("otherValue","").isEmpty()){
                isAllow = false
                break
            }
        }
        return isAllow
    }

    /**
     * 是否支持通讯录选择
     */
    private fun isSikadwaContactPick(): Boolean{
        val intentContact = Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI)
        val resolveInfoCType = requireContext().packageManager.resolveActivity(intentContact, PackageManager.MATCH_DEFAULT_ONLY)
        return resolveInfoCType != null
    }

    /**
     * 是否全为数字
     */
    private fun isSikadwaAllNumber(text: String?): Boolean {
        if (text.isNullOrEmpty()){
            return false
        }
        val formatLct = "^-?\\d+\\.?\\d*$"
        val patternLct = Pattern.compile(formatLct)
        return patternLct.matcher(text.trim()).matches()
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(EventType.PAGE.PAGE_STEP_CONTACT_END,"")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}